package com.xy6.model.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.xy6.model.api.vo.MyJob;
import com.xy6.model.bean.wrapper.MyJobWrapper;
import com.xy6.model.service.monitor.MyTaskMonitor;

/**
 * job操作工具类
 * 
 * @author zhang
 * @since 
 */
public class MyJobUtils {

	private MyJobUtils(){
	}
	
	/**
	 * 检查job中顶点、边是否合法
	 * 
	 * @param job
	 * @return
	 */
	public static boolean verify(MyJob job){
		if(null == job){
			return false;
		}
		// 顶点、边不为空
		if(StringUtils.isEmpty(job.getTaskIds()) || StringUtils.isEmpty(job.getLines())){
			return false;
		}
		// 顶点在边集合中一定存在
		Set<String> edgeV = new HashSet<>(10);
		String[] lines = job.getLines().split(";");
		Set<String> endV = new HashSet<>(10);
		for(String line : lines){
			String[] v = line.split(",");
			edgeV.addAll(Arrays.asList(v));
			endV.add(v[1]);
		}
		lines = null;
		List<String> vertex = Arrays.asList(job.getTaskIds().split(","));
		for(String id : vertex){
			if (!edgeV.contains(id)) {
				return false;
			}
		}
		// 边集合的点在顶点中一定存在
		for(String elem : edgeV){
			if (!vertex.contains(elem)) {
				return false;
			}
		}
		// 只有一个开始顶点
		List<String> heads = new ArrayList<>(5);
		for(String elem : vertex){
			if(!endV.contains(elem)){
				heads.add(elem);
			}
		}
		endV = null;
		if(heads.size() != 1){
			return false;
		}
		heads = null;
		edgeV = null;
		vertex = null;
		
		return true;
	}
	
	/**
	 * 检查依赖的task是否执行完。无需判断null
	 * 
	 * @param taskId
	 * @param job
	 * @return
	 */
	public static boolean isPreTaskFinished(String taskId, MyJobWrapper job){
		// 检查依赖的task是否执行完。无需判断null
		List<String> preTaskIds = job.getPreTasks().get(taskId);
		boolean preFinished = true;
		for(String id : preTaskIds){
			if(!MyTaskMonitor.isTaskEnd(job.getId(), id)){
				preFinished = false;
				break;
			}
		}
		return preFinished;
	}
	
}
